//
// Created by LoveHoneyYou on 2024-11-16.
//

#ifndef WEBSERVER_EVENTLOOP_H
#define WEBSERVER_EVENTLOOP_H
#include "Channel.h"
#include "Dispatcher.h"
#include <thread>
#include <queue>
#include <mutex>

enum class ElemType : char
{
    ADD,
    DELETE,
    MODIFY
};

struct ChannelElement
{
    ElemType type_;
    Channel* channel;
};

class Dispatcher;
class EventLoop
{
public:
    EventLoop();
    EventLoop(const std::string& thread_name);
    ~EventLoop();

    int Run();
    int Event_Active(int fd, int event);
    int Add_Task(Channel* channel, const ElemType& type);
    int Process_Task_Queue();
    int Add(Channel* channel);
    int Remove(Channel* channel);
    int Modify(Channel* channel);

    int Free_Channel(Channel* channel);
    int Read_Message();

    inline std::thread::id Get_Thread_Id()
    {
        return thread_id_;
    }

    inline std::string Get_Thread_Name()
    {
        return thread_name_;
    }

    static int Read_Local_Message(void* args);

private:
    void Task_Wake_Up();
private:
    bool is_quit_;
    Dispatcher* dispatcher_;
    std::queue<ChannelElement*> task_queue_;
    std::unordered_map<int,Channel*> channel_map_;
    std::thread::id thread_id_;
    std::string thread_name_;
    std::mutex mutex_;
    int socket_pair_[2];
};





#endif//WEBSERVER_EVENTLOOP_H
